import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { User, LoginRequest } from '@/types';
import { login as loginApi, verifyUserPassword } from '@/api/user';
import { ElMessage } from 'element-plus';

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null);
  const token = ref<string>('');

  // 计算属性
  const isLoggedIn = computed(() => !!user.value);
  const isAdmin = computed(() => user.value?.userType === '0');
  const userId = computed(() => user.value?.userId);

  // 初始化（从localStorage恢复登录状态）
  const initUser = () => {
    const storedUser = localStorage.getItem('user');
    const storedToken = localStorage.getItem('token');
    if (storedUser) {
      user.value = JSON.parse(storedUser);
    }
    if (storedToken) {
      token.value = storedToken;
    }
  };

  // 登录
  const login = async (loginData: LoginRequest) => {
    try {
      // 先验证密码
      const verifyResult = await verifyUserPassword(loginData.username, loginData.password);
      
      if (verifyResult.operateResult === 'SUCC') {
        // 密码验证通过，获取用户信息
        const response = await loginApi(loginData);
        
        if (response.operateResult === 'SUCC' && response.data && response.data.length > 0) {
          // 查找精确匹配的用户名
          const foundUser = response.data.find(user => user.username === loginData.username);
          
          if (!foundUser) {
            ElMessage.error('用户不存在');
            return false;
          }
          
          if (foundUser && foundUser.userId) {
            // 检查账号状态
            if (foundUser.status === '1') {
              ElMessage.error('账号已被禁用，无法登录');
              return false;
            }
            
            // 确保 userType 有值，如果数据库中没有则默认为普通用户
            if (!foundUser.userType) {
              foundUser.userType = '1'; // 默认为普通用户
            }
            
            // 确保 status 有值，如果数据库中没有则默认为正常状态
            if (!foundUser.status) {
              foundUser.status = '0'; // 默认为正常状态
            }
            
            // 登录成功
            user.value = foundUser;
            token.value = `user_${foundUser.userId}_${Date.now()}`;
            
            // 保存到localStorage
            localStorage.setItem('user', JSON.stringify(foundUser));
            localStorage.setItem('token', token.value);
            
            const isAdmin = foundUser.userType === '0';
            const userTypeText = isAdmin ? '管理员' : '普通用户';
            ElMessage.success(`登录成功，欢迎${userTypeText}！`);
            return true;
          } else {
            ElMessage.error('用户信息不完整');
            return false;
          }
        } else {
          ElMessage.error('获取用户信息失败');
          return false;
        }
      } else {
        // 密码验证失败
        ElMessage.error('用户名或密码错误');
        return false;
      }
    } catch (error: any) {
      ElMessage.error(error.message || '登录失败');
      return false;
    }
  };

  // 退出登录
  const logout = () => {
    user.value = null;
    token.value = '';
    localStorage.removeItem('user');
    localStorage.removeItem('token');
    ElMessage.success('已退出登录');
  };

  // 更新用户信息
  const updateUserInfo = (newUser: User) => {
    user.value = newUser;
    localStorage.setItem('user', JSON.stringify(newUser));
  };

  return {
    user,
    token,
    isLoggedIn,
    isAdmin,
    userId,
    initUser,
    login,
    logout,
    updateUserInfo
  };
});
